<?php

namespace app\controller;

use app\BaseController;
use app\message;
use app\model\ClueCommunicateRecord;
use app\model\CluePerson;
use app\model\SystemMenuDataPower;
use app\model\User;
use app\model\UserOrganization;
use app\model\WorkPlan;
use app\Request;
use app\service\Certificate;
use app\service\Power;
use app\service\System;
use app\service\Tasks;
use app\stateData;
use Predis\Command\Redis\HKEYS;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Validate;
use GatewayClient\Gateway;

class PlanTasks extends BaseController
{
    /**
     * 计划任务
     */
    private $plan = 1;//跟进计划
    private $tasks = 2;//任务提醒
    private $complete = 1;
    private $page = 1;

    private $message_plan_type = 1; //消息表跟进计划分类
    private $message_tasks_type = 7;//消息表任务提醒分类
    private $complete_wc = 1;//完成
    private $complete_wwc = 2;//未完成

    /************************************************************************************************************************************
     * 跟进计划
     */
    //个人查看计划任务
    public function getUidPlanList(Request $request,WorkPlan $plan,Tasks $tasks)
    {
//        $page = $request->get ('page')?:$this->page;

//        $where = $request->get ('custom_name')?:'';

//        $pageNum = $request->get ('pageNum')?:stateData::$_page;

//        $result = $plan->getUidTypeListModel($request->param ('user_login_id'),$this->plan,$where,$page,$pageNum);

        $date = $request->get ('date');
        if (empty($date)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        //月份
        $result['month'] = $tasks->getMonthPlan($request->param ('user_login_id'),$this->plan,$date);

        //统计
//        $result['statistics']['wc'] = $plan->getCompleteCount($request->param ('user_login_id'),$this->plan,$date,$this->complete_wc);
//
//        $result['statistics']['wwc'] = $plan->getCompleteCount($request->param ('user_login_id'),$this->plan,$date,$this->complete_wwc);

//        $result['statistics']['total'] = $result['statistics']['wc']+$result['statistics']['wwc'];

//        $pages['pageNumber'] = $pageNum;
//        $pages['total'] = $plan->getUidTypeListCountModel($request->param ('user_login_id'),$this->plan,$where);

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result);
    }

    //管理查看月度跟进计划
    public function getPlanList(Request $request,WorkPlan $plan,
        Power                     $power,
        Tasks                     $tasks
    ){

//        $page = $request->get ('page')?:$this->page;
        $date = $request->get ('date');
        if (empty($date)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);
//        $pageNum = $request->get ('pageNum')?:stateData::$_page;


        //查询用户数据范围
        $userIn = $power->getUserDataRange ($request->param ('user_login_id'));

//        $result['data'] = $plan->getMonthDataModel($userIn,$this->plan,$custom_name,$page,$date,$pageNum);

        //当月每月详情
        $result['month'] = $tasks->getMonthPlan($userIn,$this->plan,$date);

          //周
//        $result['week'] = $tasks->getWeekPlan($userIn,$this->plan);

//        $pages['pageNumber'] = $pageNum;
//        $pages['total'] = $plan->getTypeListCountModel($userIn,$this->plan,$custom_name,$date);

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result);
    }

    /**
     * 获取区间的计划详情
     * @param \app\Request $request
     * @param \app\model\WorkPlan $plan
     * @param \app\service\Power $power
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDayData(
        Request $request,
        WorkPlan $plan,
        Power    $power,
        CluePerson $cluePersonModel,
        \app\model\ClueEnterprise $clueEnterpriseModel,
        System $systemService,
        UserOrganization $organizationModel,
        User $userModel,
        ClueCommunicateRecord $clueCommunicateRecordModel
    ){
        $uid = $request->get('login_user_id');
        $id = $request->get ('id')?:'';
        $page = $request->get ('page')?:$this->page; //分页

        $custom_name = $request->get ('custom_name')?:'';//客户名称

        $userIn = $request->get ('uid')?:''; //需要查询用户资料的id
        $orgId = $request->get ('org')?:''; //需要查询用户资料的id

        $start_date = $request->get ('start_date').' 00:00:00'; //开始时间
        $end_date = $request->get ('end_date').' 23:59:58'; //结束时间

        $pageNum = $request->get ('pageNum')?:stateData::$_page; //每页显示多少条

        //查询已完成 未完成
        if (!empty($request->get ('complete'))){
            $complete = $request->get ('complete');
        }else{
            $complete = '1,2';
        }

        if (empty($userIn)) {
            //查询用户数据范围
            if ($orgId){
                $orgStr = $systemService->getOrgIdStr ($orgId,$organizationModel->getStructure ());
                $userIn = $userModel->getOidUidDataModel (explode (',',rtrim ($orgStr,',')));
            }else{
                $userIn = $power->getUserDataRange ($request->param ('user_login_id'));
            }
        }

        if (empty($start_date) || empty($end_date)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        if ($id){
            $result = $plan->getIdDataModel($id);
        }else{
            $result = $plan->getBetweenTimeTypeListModel($userIn,$this->plan,$custom_name,$page,$start_date,$end_date,$pageNum,$complete);
        }

        //通过客户名称查询是否有人才或者企业
        foreach ($result as &$item) {
            //通过沟通记录绑定b_id 寻找人才信息
            $gid = $clueCommunicateRecordModel->getIdFindModel ($item['b_id']);
            $fuid = $cluePersonModel->getIdPersonInfo($gid['clue_p_id']);
            if ($item['custom_name']){
                $person = $cluePersonModel->getPersonNameDataModel($item['custom_name'],$uid); //人才

                if (!empty($person)){
                    $item['link_type'] = 1; //查询人才数据
                    $item['link_id'] = $gid['clue_p_id']; //查询人才数据
                    $item['f_uid'] = $fuid['f_uid'];
                }else{ //企业
                    $enter = $clueEnterpriseModel->getEnterpriseNameDataModel ($item['custom_name'],$uid);
                    $fuid = $clueEnterpriseModel->getIdInfo($gid['clue_p_id']);
                    if (!empty($enter)){
                        if ($enter[0]['type'] == 1){
                            $item['link_type'] = 2; //注册企业
                            $item['link_id'] = $gid['clue_p_id']; //查询企业数据
                            $item['f_uid'] = $fuid['f_uid'];
                        }else{
                            $item['link_type'] = 3; //合作伙伴
                            $item['link_id'] = $gid['clue_p_id']; //查询企业数据
                            $item['f_uid'] = $fuid['f_uid'];
                        }

                    }else{
                        $item['link_type'] = '';
                        $item['link_id'] = '';
                        $item['f_uid'] = '';
                    }
                }
            }
        }
        $pages['pageNumber'] = $pageNum;
        $pages['total'] = $plan->getBetweenTimeTypeCountModel($userIn,$this->plan,$custom_name,$start_date,$end_date,$complete);

        //统计已完成 未完成
        $result['statistics']['wc'] = $plan->getCompleteCount($userIn,$this->plan,$start_date,$end_date,$this->complete_wc);
        $result['statistics']['wwc'] = $plan->getCompleteCount($userIn,$this->plan,$start_date,$end_date,$this->complete_wwc);

        $result['statistics']['total'] = $result['statistics']['wc']+$result['statistics']['wwc'];

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result,$pages);
    }

    //新增计划任务
    public function addPlan(
        Request                $request,
        WorkPlan               $plan,
        \app\model\UserMessage $message,
        Gateway                $gateway,
        CluePerson $personModel,
        \app\model\ClueEnterprise $enterpriseModel,
        ClueCommunicateRecord $clueCommunicateRecordModel
    ){
        $param = $request->post ();
        Db::startTrans();
        try {
            Validate(\app\validate\PlanTasks::class)->check ($param);

            //拼接提交人资料
            $param['create_uid'] = $uid = $request->param ('user_login_id');
            $param['type'] = $this->plan;
            //添加计划
            $planAdd = $plan->addPlanModel($param);

            //添加消息列表
            $messages = $message->addPlanModel($param['custom_name'],$param['create_uid'],$uid,$planAdd->id,$param['plan_date']);

            //查看客户名称是人才还是企业 针对性添加到沟通记录
            if ($param['custom_name']){
                //查看人才库
                $perData = $personModel->getPersonNameDataModel($param['custom_name'],$uid);
                if (!empty($perData)){
                    foreach ($perData as $perDatum) {
                        $value['clue_p_id'] = $perDatum['id'];
                        $value['communicate_content'] = $param['plan_content'];
                        $value['communicate_uid'] = $param['create_uid'];
                        $value['communicate_date'] = $param['plan_date'];
                        $value['type'] = 1;
                        $clueCommunicateRecordModel->addPersonCommunicateRecordModel ($value);
                    }
                }

                $enData =  $enterpriseModel->getEnterpriseNameDataModel($param['custom_name'],$uid);
                if (!empty($enData)){
                    foreach ($enData as $enDatum) {
                        $value['clue_p_id'] = $enDatum['id'];
                        $value['communicate_content'] = $param['plan_content'];
                        $value['communicate_uid'] = $param['create_uid'];
                        $value['communicate_date'] = $param['plan_date'];
                        $value['type'] = 2;
                        $clueCommunicateRecordModel->addPersonCommunicateRecordModel ($value);
                    }
                }
            }

//            $gateway->sendToUid($param['uid'],json_encode ($messages));
            Db::commit();
        }catch (\Exception | ValidateException $e){
            Db::rollback();
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
    }


    //删除计划任务
    public function delPlan(
        Request                $request,
        WorkPlan               $plan,
        \app\model\UserMessage $message,
        CluePerson $personModel,
        \app\model\ClueEnterprise $enterpriseModel,
        ClueCommunicateRecord $clueCommunicateRecordModel
    ){
        $id = $request->post ('id');

        if (empty($id)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);
        Db::startTrans();
        try {
            //查询该id对应客户名称
            $param = $plan->getIdFindModel($id);

            //删除人才或企业沟通记录
//            if ($param['type'] == 1){
//                $perData = $personModel->getPersonNameDataModel($param['custom_name']);
//
//                if (!empty($perData)){
//                    foreach ($perData as $item) {
//                        $clueCommunicateRecordModel->delWhereDataModel($item['id'],$param['plan_content'],$param['create_uid']['id'],$param['type'],$param['plan_date']);
//                    }
//                }
//            }else{
//                $enData =  $enterpriseModel->getEnterpriseNameDataModel($param['custom_name']);
//                print_r ($enData);die;
//                if (!empty($enData)){
//                    foreach ($enData as $items) {
//            $clueCommunicateRecordModel->delWhereDataModel($items['id'],$param['plan_content'],$param['create_uid']['id'],$param['type'],$param['plan_date']);
            $clueCommunicateRecordModel->delPersonCommunicateRecordModel($param['b_id']);
//                    }
//                }
//            }

            //删除计划任务
            $plan->delIdModel($id);
            //删除信息提醒
            $message->delBidMessageModel ($id);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }

        return ReJson (message::$SUCC_CODE,message::$SUCC_DATELE_DATA);
    }


    //编辑计划任务
    public function editPlan(
        Request                   $request,
        WorkPlan                  $plan,
        CluePerson                $personModel,
        \app\model\ClueEnterprise $clueEnterpriseModel,
        ClueCommunicateRecord     $clueCommunicateRecordModel,
        \app\model\UserMessage $messageModel
    ){
        $param = $request->post ();

        if (empty($param['id'])) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        try {
            //查询计划任务详情
            $data = $plan->getIdFindModel ($param['id']);

            //编辑计划任务
            $plan->editDataModel($param);

            //编辑消息表
            $mess = $messageModel->getWhereDataModel($data['plan_date'],$data['create_uid']['id'],1,$data['id']);

            if ($mess){
                foreach ($mess as $messId) {
                    $messageModel->esitIdFindModel($messId['id'],['execution_date'=>$param['plan_date']]);
                }
            }

            //编辑沟通记录表
            $clueCommunicateRecordModel->editIdCommunicate ($data['b_id'],['next_communicate_date'=>$param['plan_date'],'next_plan_content'=>$param['plan_content']]);



        }catch (\Exception $e){
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE,message::$SUCC_UPDATE);
    }


    //完成计划任务
    public function completePlan(Request $request,WorkPlan $plan)
    {
        $id = $request->post ('id');

        if (empty($id)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        $plan->editDataModel([
            'id'=>$id,
            'is_complete'=>$this->complete
        ]);

        return ReJson (message::$SUCC_CODE,message::$SUCC_COMPLETE_PLAN);
    }


    /***************************************************************************************************************************
     * 任务提醒
     */

    //添加任务提醒
    public function addTasks(Request $request,WorkPlan $plan,\app\model\UserMessage $message,Gateway $gateway)
    {
        $param = $request->post ();
        try {
            Validate(\app\validate\PlanTasks::class)->scene('tasks')->check ($param);

            //拼接提交人资料
            $param['create_uid'] = $uid = $request->param ('user_login_id');
            $param['type'] = $this->tasks;

            //添加计划
            $planAdd = $plan->addPlanModel($param);

            //添加消息列表
            $messages = $message->addPlanModel($param['custom_name'],$param['create_uid'],$uid,$planAdd->id,$param['plan_date']);

//            $gateway->sendToUid($param['create_uid'],json_encode ($messages));
        }catch (\Exception | ValidateException $e){
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
    }

    //个人查看任务提醒
    public function getUidTasksList(Request $request,WorkPlan $plan,Tasks $tasks)
    {
        $date = $request->get ('date');
        if (empty($date)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        //月份
        $result['month'] = $tasks->getMonthPlan($request->param ('user_login_id'),$this->tasks,$date);

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result);
    }

    //管理查看任务提醒
    public function getTasksList(
        Request $request,
        WorkPlan $plan,
        Power   $power,
        Tasks $tasks
    ){

        $date = $request->get ('date');

        if (empty($date)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        //查询用户数据范围
        $userIn = $power->getUserDataRange ($request->param ('user_login_id'));

        //当月每一天详情
        $result['month'] = $tasks->getMonthPlan($userIn,$this->tasks,$date);

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result);
    }

    /**
     * 获取任务提醒某有一天数据
     * @param \app\Request $request
     * @param \app\model\WorkPlan $plan
     * @param \app\service\Power $power
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTasksDayData(
        Request $request,
        WorkPlan $plan,
        Power    $power
    ){
        $page = $request->get ('page')?:$this->page;

        $custom_name = $request->get ('custom_name')?:'';

        $userIn = $request->get ('uid')?:'';

        $start_date = $request->get ('start_date')."00:00:00";
        $end_date = $request->get ('end_date')."23:59:58";

        $pageNum = $request->get ('pageNum')?:stateData::$_page;

        //查询已完成 未完成
        if (!empty($request->get ('complete'))){
            $complete = $request->get ('complete');
        }else{
            $complete = '1,2';
        }

        if (empty($userIn)) {
            //查询用户数据范围
            $userIn = $power->getUserDataRange ($request->param ('user_login_id'));
        }
//print_r ($userIn);die;
        if (empty($start_date) || empty($end_date)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        $result = $plan->getBetweenTimeTypeListModel($userIn,$this->tasks,$custom_name,$page,$start_date,$end_date,$pageNum,$complete);

        //统计已完成 未完成
        $result['statistics']['wc'] = $plan->getCompleteCount($userIn,$this->tasks,$start_date,$end_date,$this->complete_wc);
        $result['statistics']['wwc'] = $plan->getCompleteCount($userIn,$this->tasks,$start_date,$end_date,$this->complete_wwc);

        $result['statistics']['total'] = $result['statistics']['wc']+$result['statistics']['wwc'];

        $pages['pageNumber'] = $pageNum;
        $pages['total'] = $plan->getBetweenTimeTypeCountModel($userIn,$this->tasks,$custom_name,$start_date,$end_date,$complete);

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result,$pages);
    }

}